package model

import "github.com/jinzhu/gorm"

// * bind orm
type AdviceModel struct {
	gorm.Model
	Email   string `gorm:"not null;type :varchar(128)" json:"email"`
	Title     string `gorm:"not null;type :varchar(128)" json:"title"`
	Content   string `gorm:"not null;type :varchar(500)" json:"content"`
}



// * 设置表名
func (advice AdviceModel) TableName() string {
	return "advices"
}

// * 添加advice到数据库
func (advice AdviceModel) Create() error {
	return DB.Self.Create(&advice).Error
}

// * 删除某个advice
func (advice AdviceModel) Delete() error {
	return DB.Self.Delete(&advice).Error
}

// * Update advice
func (advice AdviceModel) Update() error {
	return DB.Self.Save(&advice).Error
}

// * 获取某一条advice
func (advice AdviceModel) Get() (AdviceModel, error) {
	return advice, DB.Self.First(&advice, advice.ID).Error
}

// * 获取所有advice
func (advice AdviceModel) GetAll() (uint64, []AdviceModel, error) {

	var advices []AdviceModel
	var count uint64

	if err := DB.Self.Table(advice.TableName()).Count(&count).Error; err != nil {
		return count, advices, err
	}
	if err := DB.Self.Find(&advices).Error; err != nil {
		return count, advices, err
	}
	return count, advices, nil

}